package thread.定时器;

import java.util.PriorityQueue;

// 模拟TimerTask(定时器任务)
class MyTimerTask implements Comparable<MyTimerTask>{
    // 要执行的任务
    private Runnable runnable;
    // 执行任务的时间
    private long time;

    //模拟 TimerTask 函数
    public MyTimerTask(Runnable runnable,long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        // 让队首元素是最小的元素
        return (int)(this.time-o.time);
    }

    public Long getTime() {
        return time;
    }

    public Runnable getRunnable() {
        return runnable;
    }
}

// 模拟定时器  
class MyTimer {

    private Object obiect = new Object();
    // 使用一个数据结构，保存任务数据（优先级队列）
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();

    // 实现 schedule(时间表) 函数
    public void schedule(Runnable runnable, long delay) {
        synchronized (obiect) {
            queue.offer(new MyTimerTask(runnable, delay));
            obiect.notify();
        }
    }

    // 扫描线程
    public MyTimer() {
        Thread t = new Thread(() -> {
            // 不停的扫描队首，观察是否到时间
            while (true) {
                synchronized (obiect) {
                    // 队列为空的时候，阻塞等待
                    while (queue.isEmpty()) {
                        try {

                            obiect.wait();

                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    MyTimerTask task = queue.peek();
                    // 比较队首元素是否可以执行了
                    long curTime = System.currentTimeMillis();
                    if (curTime >= task.getTime()) {
                        // 达到的话开始执行任务 执行完删除
                        task.getRunnable().run();
                        queue.poll();
                    }else {

                        try {

                            obiect.wait(task.getTime() - curTime);

                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }

                }
            }
        });
        t.start();
    }


}

public class Demo2 {
}
